// web/src/app/api/(social)/workspaces/[id]/route.ts

import {NextRequest, NextResponse} from "next/server";
import {db} from "@/lib/db";

export async function GET(req: NextRequest) {
    const searchParams = req.nextUrl.searchParams;
    const id = req.nextUrl.pathname.slice(
        req.nextUrl.pathname.lastIndexOf('/') + 1
    );

    let userId = (searchParams.get('userId'))
    if (userId) {
        const workspaces = await db.workspace.findMany({
            where: {
                userId
            }
        })
        return NextResponse.json(workspaces)
    }

    const workspace = await db.workspace.findUnique({
        where: {
            id
        }
    })

    return NextResponse.json(workspace)
}

export async function DELETE(req: NextRequest, {params}: { params: { id: string } }) {
    const id = params.id

    const workspace = await db.workspace.delete({
        where: {
            id
        }
    })

    return NextResponse.json(workspace)
}

export async function PATCH(req: NextRequest,
                            {params}: { params: { id: string } }) {
    let values = await req.json()
    console.log('update workspace', values)

    const workspace = await db.workspace.findUnique({
        where: {
            id: params.id
        }
    })

    if (!workspace) return new NextResponse('Not Found', {status: 404})

    const newWorkspace = await db.workspace.update({
        where: {
            id: params.id
        },
        data: values
    })

    return NextResponse.json(newWorkspace)
}

export async function PUT(req: NextRequest,
                          {params}: { params: { id: string } }) {
    let values = await req.json()
    console.log('update workspace', values)

    const workspace = await db.workspace.findUnique({
        where: {
            id: params.id
        }
    })

    if (!workspace) return new NextResponse('Not Found', {status: 404})

    const newWorkspace = await db.workspace.update({
        where: {
            id: params.id
        },
        data: values
    })

    return NextResponse.json(newWorkspace)
}